package com.github.shiqiyue.myadmin.controller.system;

import com.github.shiqiyue.myadmin.controller.base.AdminBaseController;
import com.github.shiqiyue.myadmin.entity.system.User;
import com.github.shiqiyue.myadmin.service.system.user.UserService;
import com.github.shiqiyue.myadmin.vo.rep.base.RepBase;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/***
 * 后台登录-控制器
 *
 * @author wwy
 *
 */
@Controller
@RequestMapping("admin")
public class AdminMainController extends AdminBaseController {

	private static final Logger log = LoggerFactory.getLogger(AdminMainController.class);

	@Autowired
	private UserService userService;

	@Autowired
    @Qualifier("adminPasswordEncoder")
	private PasswordEncoder passwordEncoder;

	/**
	 * 访问登录页
	 *
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value = "/login")
    public String toLogin(HttpServletRequest request, HttpSession httpSession, Model model) {
        // 获取认证失败的exception
        AuthenticationException exception = (AuthenticationException) httpSession
                .getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        if (exception != null) {
            model.addAttribute("loginError", exception.getMessage());
        }
		httpSession.invalidate();
		httpSession = request.getSession(true);
        return "pages/login";
    }

    /***
	 * 访问系统首页
	 * @return
	 */
	@RequestMapping(value = "/main")
	public ModelAndView loginIndex() {
		ModelAndView mv = this.getModelAndView();
        mv.setViewName("pages/main");
		return mv;
	}

	/***
	 * 获取登录的用户信息
	 * @return
	 */
	@PreAuthorize("hasRole('ADMIN')")
	@PostMapping("userinfo")
	@ResponseBody
    public RepBase getUserInfo() {
		User loginUser = userService.selectById(getLoginUserId());
        return RepBase.newIntance().setCommonSuccess().setData(loginUser);
	}

	/***
	 * 修改个人用户信息-页面
	 * @param model
	 * @return
	 */
	@PreAuthorize("hasRole('ADMIN')")
	@GetMapping(value = "userinfo/edit")
	public String toEditUserInfo(Model model) {
		User loginUser = userService.selectById(getLoginUserId());
		model.addAttribute("loginUser", loginUser);
		return "pages/userinfo-edit";
	}

	/***
	 * 修改用户个人信息-动作
	 * @param user
	 * @return
	 */
	@PreAuthorize("hasRole('ADMIN')")
	@PostMapping(value = "userinfo/edit")
	@ResponseBody
    public RepBase editUserInfo(User user) {
		User oldUser = userService.selectById(user.getId());
		oldUser.setNickname(user.getNickname());
		oldUser.setEmail(user.getEmail());
		oldUser.setPhone(user.getPhone());
		oldUser.setPhotoUrl(user.getPhotoUrl());
		oldUser.setRemarks(user.getRemarks());
		if (StringUtils.isNotBlank(user.getPassword())) {
			oldUser.setPassword(passwordEncoder.encode(user.getPassword()));
		}
		userService.updateById(oldUser);
        return RepBase.newIntance().setCommonSuccess();
	}

}
